<?php
/**
 * TiersTable.php
 */

namespace RHX\Model\Table;

use Zend\Db\Adapter\Adapter;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Db\ResultSet\ResultSet;
use RHX\Model\Object\Tiers;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Expression;

class TiersTable extends AbstractTableGateway {

    /**
     * Nom de la table dans la base de données
     *
     * @var string $table
     */
    protected $table = 'rh_tiers';

    /**
     * Constructeur de la Classe
     * 
     * @param \RHX\Model\Table\Adapter $adapter
     */
    public function __construct(Adapter $adapter) {
	$this->adapter			 = $adapter;
	$this->resultSetPrototype	 = new ResultSet();
	$this->resultSetPrototype->setArrayObjectPrototype(new Tiers($adapter));
	$this->initialize();
    }

    /**
     * Tous les "Tiers" 
     *
     * @param string $order Ordre d'affichage
     * @return type
     */
    public function getAll($order = 'id ASC') {
	return $this->select(function(Select $select) use($order) {
			    $select->order($order);
			});
    }
    
    /**
     * Effacer un Tiers
     *
     * @param int $id
     * @return int 
     */
    public function erase($id) {
	return $this->delete(array('id' => $id));
    }
    
    /**
     * Récupérer un Tiers
     *
     * @param type $id 
     * @return Ters
     * @throws \Exception
     */
    public function get($id) {
	$row = $this->select(array('id' => $id))
		->current();
	if (!$row)
	    throw new \Exception("Erreur 71 : Le tiers #$id n'a pas été trouvé");

	return $row;
    }
    
    /*
     * sauvegarder un Tiers
     * @return int : id du Tiers sauvé
     **/
    public function save(Tiers $tiers){       
        $data	 = array();
        
        $fieldString = array('libelle', 'contact', 'adresse', 'siret', 'website', 'phone', 'fax', 'mail', 'photo', 'rib');
        
        foreach ($fieldString as $f) : 
            $data[$f] = $tiers->$f;
        endforeach;
        
        $dWk = array('lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche') ;
        foreach ($dWk as $day) : 
            $day_ouv = $day.'_ouverture';
            $day_fer = $day.'_fermeture';
            
            $data[$day]     = $tiers->$day;
            $data[$day_ouv] = $tiers->$day_ouv;
            $data[$day_fer] = $tiers->$day_fer;
        endforeach;
        
        // save / update
	$id	 = (int) $tiers->id;
	if ($id == 0)
	    $this->insert($data);
	elseif ($this->get($id))
	    $this->update($data, array('id' => $id));
	else
	    throw new \Exception("Impossible de trouver #$id");

	if ($id == 0)
	    return $this->lastInsertValue;
	else
	    return $id;
        
    }
}

